package com.collegeproject.weatherapp.fragments;

import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.collegeproject.weatherapp.R;
import com.collegeproject.weatherapp.StartActivity.FragmentListener;
import com.collegeproject.weatherapp.library.AsyncResponse;
import com.collegeproject.weatherapp.library.ConnectionDetector;
import com.collegeproject.weatherapp.library.HTTPfunctions;

public class RegisterFragment extends Fragment implements AsyncResponse {
	Button btnRegister, btnBack;
	EditText inputUserName, inputPass, inputRePass, inputFirst, inputLast,
			inputEmail;
	TextView registerError, _registerURL;

	private String mPassword, mUserName, mFirst, mLast, mEmail;

	private static FragmentListener _listener;
	
	ConnectionDetector cd;

	private static final String TAG = "RegisterFragment";
	// private static String localRegisterURL = "http://10.0.2.2:8080/WeatherAppService.svc/rest/register";
	private static String registerURL = "http://x00068868.cloudapp.net/WeatherAppService.svc/rest/register";

	private static final String POST = "POST";

	public static RegisterFragment newInstance(FragmentListener listener) {
		RegisterFragment f = new RegisterFragment();
		_listener = listener;
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.register, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initialiseViews();
		cd = new ConnectionDetector(getActivity());
	}

	@Override
	public void onStart() {
		
		inputEmail.setOnEditorActionListener(new OnEditorActionListener() {
			
			@SuppressWarnings("static-access")
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					mUserName = inputUserName.getText().toString().trim();
					mPassword = inputPass.getText().toString().trim();

					mFirst = inputFirst.getText().toString().trim();
					mLast = inputLast.getText().toString().trim();
					mEmail = inputEmail.getText().toString().trim();

					// try to register
					attemptRegister(mPassword, mUserName, mFirst, mLast, mEmail);
					
					// hide the keyboard
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									getActivity().INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
					
					return true;
				}
				return false;
			}
		});
		
		// back to login fragment
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// back to login fragment
				_listener.onSwitchToNextFragment();

			}
		});

		// try to register
		btnRegister.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mUserName = inputUserName.getText().toString().trim();
				mPassword = inputPass.getText().toString().trim();

				mFirst = inputFirst.getText().toString().trim();
				mLast = inputLast.getText().toString().trim();
				mEmail = inputEmail.getText().toString().trim();

				// try to register
				attemptRegister(mPassword, mUserName, mFirst, mLast, mEmail);
			}
		});
		super.onStart();
	}

	private void attemptRegister(String mPassword, String mUserName,
			String mFirst, String mLast, String mEmail) {

		inputUserName.setError(null);
		inputPass.setError(null);
		inputFirst.setError(null);
		inputLast.setError(null);
		inputEmail.setError(null);

		boolean cancel = false;
		View focusView = null;

		// Check for a valid user name.
		if (TextUtils.isEmpty(mUserName)) {
			inputUserName.setError(getString(R.string.error_field_required));
			focusView = inputUserName;
			cancel = true;
		} else if (mUserName.length() < 6) {
			inputUserName.setError(getString(R.string.error_field_lesschar));
			focusView = inputUserName;
			cancel = true;
		}

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			inputPass.setError(getString(R.string.error_field_required));
			focusView = inputPass;
			cancel = true;
		} else if (mPassword.length() < 6) {
			inputPass.setError(getString(R.string.error_invalid_password));
			focusView = inputPass;
			cancel = true;
		}

		// check for valid email address
		if (!mEmail.contains("@")) {
			inputEmail.setError(getString(R.string.error_invalid_email));
			focusView = inputEmail;
			cancel = true;
		}

		// check for valid first name
		if (TextUtils.isEmpty(mFirst)) {
			inputFirst.setError(getString(R.string.error_field_required));
			focusView = inputFirst;
			cancel = true;
		}

		// check for valid last name
		if (TextUtils.isEmpty(mLast)) {
			inputLast.setError(getString(R.string.error_field_required));
			focusView = inputLast;
			cancel = true;
		}

		if (cancel) {
			focusView.requestFocus();
		} else {

			try {
				Boolean connected = cd.isConnectingToInternet();
				if (connected){

					// //convert parameters into JSON object
					JSONObject holder = new JSONObject();
					holder.put("UserName", mUserName);//
					holder.put("Password", mPassword);
					holder.put("Email", mEmail);
					holder.put("FirstName", mFirst);
					holder.put("LastName", mLast);

					// pass the results to a string builder/entity
					StringEntity se = new StringEntity(holder.toString());

					// call the register web service
					HTTPfunctions task = new HTTPfunctions(getActivity(), POST,
							se);
					task.listener = this;
					task.execute(new String[] { registerURL });
				} else {
					registerError.setText("No internet connection available");
					registerError.setVisibility(View.VISIBLE);
				}
			} catch (Exception ex) {
				Log.e(TAG, "Attempt Register " + ex.getMessage());
			}
		}
	}

	private void initialiseViews() {
		btnBack = (Button) getView().findViewById(R.id.button_register_back);
		btnRegister = (Button) getView().findViewById(R.id.button_register);
		inputUserName = (EditText) getView().findViewById(
				R.id.editTextRegisterUsername);
		inputPass = (EditText) getView().findViewById(
				R.id.editTextRegisterPass1);
		inputRePass = (EditText) getView().findViewById(
				R.id.editTextRegisterPass2);
		inputFirst = (EditText) getView().findViewById(
				R.id.editTextRegisterFirstName);
		inputLast = (EditText) getView().findViewById(
				R.id.editTextRegisterLastName);
		inputEmail = (EditText) getView().findViewById(
				R.id.editTextRegisterEmail);

		registerError = (TextView) getView().findViewById(R.id.register_error);
		_registerURL = (TextView) getView().findViewById(R.id.registert_url);
	}

	@Override
	public void processFinish(String result) { // result from async task
		try {
			JSONObject jsonObject = new JSONObject(result);
			int success = Integer.parseInt(jsonObject.getString("Success"));
			if (success == 0) {
				// toast to user of confirmation of registration
				Toast.makeText(getActivity(), "Registered successfully !",
						Toast.LENGTH_SHORT).show();

				// switch to login fragment
				_listener.onSwitchToNextFragment();

			} else {
				// display error from result
				registerError.setText(jsonObject.getString("ErrorMessage"));
				registerError.setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			Log.e(TAG, "Register processs result " + e.getMessage());
		}
	}
}